package headbean;

import factory.ExcelHeadMapFactory;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 表格数据专用的map，带顺序，而且初始化的时候，依据指定的表头变量字段名确定导出数据的顺序
 *
 * @author feng
 */
public class ExcelDataLinkedHashMap extends LinkedHashMap<String, Object> {

    private static final long serialVersionUID = -8554095999151235982L;

    /**
     * 头部字段名缓存
     */
    private final Set<String> headColumnNamesCache;

    private final Map<String, Class<? extends Converter>> convertClassMap;

    /**
     * ExcelDataLinkedHashMap构造器
     *
     * @param headColumnNames 表头字段变量名，例如：[name,studentNo,age,className]
     */
    public ExcelDataLinkedHashMap(List<Object> headColumnNames, Class<? extends ExcelHeadMapInterface> headBeanClass) {
        convertClassMap = ExcelHeadMapFactory.COLUMN_CONVERTER_MAP.get(headBeanClass);
        // 字段名去重
        List<String>  headColumnStringNames = headColumnNames.stream().distinct().map(Object::toString).collect(Collectors.toList());
        // 构建字段名缓存
        this.headColumnNamesCache = new HashSet<>(headColumnStringNames);
        // 指定列数据排列顺序
        for (String headColumnName : headColumnStringNames) {
            this.put(headColumnName, null);
        }
    }

    @Override
    public Object put(String key, Object value) {
        // 只保存字段名缓存中的key以及value
        if (headColumnNamesCache.contains(key)) {
            // 处理转换器
            Class<? extends Converter> convertClass = convertClassMap.get(key);
            if(convertClass != null && value != null) {
                Converter converter = ExcelHeadMapFactory.CONVERTER_BEAN_MAP.get(convertClass);
                return super.put(key, converter.mapTo(value));
            }
            return super.put(key, value);
        }
        return null;
    }
}
